package com.tiny.mirror.service.product.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.tiny.mirror.basic.common.enums.IBaseEnum;
import com.tiny.mirror.basic.common.json.serializer.BigDecimalToStringSerializer;
import com.tiny.mirror.basic.common.json.serializer.IBaseEnumJsonSerializer;
import com.tiny.mirror.basic.web.config.AbstractWebConfig;
import com.tiny.mirror.basic.web.setting.RuntimeSettings;
import java.math.BigDecimal;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

@Configuration
public class WebMvcConfig extends AbstractWebConfig {

  @Value("${spring.application.name}")
  private String applicationName;

  @Bean
  public RuntimeSettings runtimeSettings() {
    RuntimeSettings settings = RuntimeSettings.get();
    settings.setApplicationName(applicationName);
    return settings;
  }

  @Override
  public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    super.extendMessageConverters(converters);
    for (HttpMessageConverter<?> converter : converters) {
      if (converter instanceof MappingJackson2HttpMessageConverter) {
        SimpleModule module = new SimpleModule();
        module.addSerializer(BigDecimal.class, new BigDecimalToStringSerializer());
        module.addSerializer(IBaseEnum.class, new IBaseEnumJsonSerializer());
        ObjectMapper objectMapper =
            ((MappingJackson2HttpMessageConverter) converter).getObjectMapper();
        objectMapper.registerModule(module);
      }
    }
  }
}